package com.joyzone.weixin.util;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.joyzone.weixin.exception.WeixinException;
import com.joyzone.weixin.menu.Menu;

/**
 * 自定义菜单工具类
 * 
 * @author yulm
 * @date   2014-2-19
 */
public class MenuUtil {

	private static Logger logger = LoggerFactory.getLogger(MenuUtil.class);
	
	/**
	 * 创建菜单
	 * @param menu
	 * @param token
	 */
	public static boolean createMenu(Menu menu, String accessToken) {
		boolean result = false;
		String url = StringUtil.formatParaUrl(Constants.URL_Menu_Create,new String[]{accessToken});
		// 将菜单对象转成json字符串
		String jsonMenu = JSONObject.fromObject(menu).toString();
		// 发起post请求创建菜单
		try {
			CommonUtil.httpsRequest2Json(url, "POST", jsonMenu);
			result = true;
		} catch (WeixinException e) {
			logger.error("创建菜单失败 errcode:{} errmsg:{}",e.errcode,e.message);
		}
		return result;
	}
	
	/**
	 * 删除菜单
	 * @param menu
	 * @param token
	 */
	public static boolean deleteMenu(Menu menu, String accessToken) {
		boolean result = false;
		String url = StringUtil.formatParaUrl(Constants.URL_Menu_Delete,new String[]{accessToken});
		// 发起post请求创建菜单
		try {
			CommonUtil.httpsRequest2Json(url, "GET", null);
			result = true;
		} catch (WeixinException e) {
			logger.error("删除菜单失败 errcode:{} errmsg:{}",e.errcode,e.message);
		}
		return result;		
	}
	
	/**
	 * 查询菜单
	 * @param menu
	 * @param token
	 */
	public static String getMenu(Menu menu, String accessToken) {
		String result = null;
		String url = StringUtil.formatParaUrl(Constants.URL_Menu_Get,new String[]{accessToken});
		// 发起post请求创建菜单
		try {
			result = CommonUtil.httpsRequest2Json(url, "GET", null).toString();
		} catch (WeixinException e) {
			logger.error("查询菜单失败 errcode:{} errmsg:{}",e.errcode,e.message);
		}
		return result;		
	}
}
